package com.infosys.newSimpleInvertedIndex.models;

import java.util.*;

import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;

public class ParsedDoc {
    private String id;
    private ImmutableList<Term> documentTerms;
    private ImmutableMap<String, Integer> wordFrequency;
    // LESSON: attempted to remove this peorperty, added too much hassle .getTerm()
    private ImmutableSet<String> uniqueWords;

    public ParsedDoc(List<Term> terms, String id) {
        // check if terms and id valid
        Preconditions.checkNotNull(id);
        Preconditions.checkNotNull(terms);
        this.id = id;
        this.documentTerms = ImmutableList.copyOf(terms);
        // generate the word frequency
        calcTermFrequency();
        // generate unique words
        generateUniqueWords();
    }

    private void calcTermFrequency() {
        Map<String, Integer> wordFrequencyTemp = new HashMap<>();
        for (Term term : this.documentTerms){
            if (!wordFrequencyTemp.containsKey(term.getTerm())){
                wordFrequencyTemp.put(term.getTerm(), 0);
            }
            wordFrequencyTemp.put(term.getTerm(), wordFrequencyTemp.get(term.getTerm()) + 1);
        }
        this.wordFrequency = ImmutableMap.copyOf(wordFrequencyTemp);
    }

    private void generateUniqueWords() {
        Set<String> uniqueWordsTemp = new HashSet<>();
        for (Term term : this.documentTerms){
            uniqueWordsTemp.add(term.getTerm());
        }
        this.uniqueWords = ImmutableSet.copyOf(uniqueWordsTemp);
    }

    public int getWordFrequency(String word) {
        return this.wordFrequency.getOrDefault(word, 0);
    }

    public boolean isEmpty() {
        return this.documentTerms.isEmpty();
    }

    public Set<String> getUniqueWords() {
        return this.uniqueWords;
    }

    public List<Term> getTerms() {
        return this.documentTerms;
    }

    public String getId() {
        return this.id;
    }
}